
from goods.serializers import SKUSerializer
from rest_framework.generics import GenericAPIView, CreateAPIView, RetrieveAPIView, UpdateAPIView
from rest_framework.viewsets import GenericViewSet
from rest_framework import mixins, status
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import permissions
from django_redis import get_redis_connection
from rest_framework.decorators import action
import logging
import re
from rest_framework_jwt.views import ObtainJSONWebToken
from rest_framework.permissions import IsAuthenticated

from .models import User
from . import serializers
from verifications.serializers import ImageCodeCheckSerializer
# from meiduo_mall.utils.permissions import IsOwner
from .utils import get_user_by_account
from . import constants
from goods.models import SKU
from .serializers import UserBrowseHistorySerializer
# from goods.serializers import SKUSerializer
# from carts.utils import merge_cart_cookie_to_redis

# Create your views here.


class UserBrowseHistoryView(CreateAPIView):
    """用户浏览记录接口"""

    # 指定权限：必须登录用户才能保存浏览记录
    permission_classes = [IsAuthenticated]
    # 指定序列化器
    serializer_class = serializers.UserBrowseHistorySerializer

    def get(self, request):
        """读取用户浏览记录
        """
        # 创建连接到redis的对象
        redis_conn = get_redis_connection('history')

        # 读取出所有的sku_id信息
        sku_ids = redis_conn.lrange('history_%s' % request.user.id, 0, -1)

        # sku模型对象的容器
        sku_list = []
        # 遍历sku_ids，取出sku_id,查询sku
        for sku_id in sku_ids:
            sku = SKU.objects.get(id=sku_id)
            sku_list.append(sku)

        # 将sku_listJ进行序列化
        serializer = SKUSerializer(sku_list, many=True)

        return Response(serializer.data)




class VerifyEmailView(APIView):
    """
    验证邮箱
    目的：获取token，读取user_id,查询当前要认证的用户，将用户的email_active设置为True

    """
    def get(self, request):
        #获取token
        token = request.query_params.get('token')
        if token is None:
            return Response({'message':'缺少token'},status=status.HTTP_400_BAD_REQUEST)
        #读取出user_id,查询当前要认证的用户
        user = User.check_verify_email_token(token)
        if user is None:
            return Response({'message':'无效的token'},status=status.HTTP_400_BAD_REQUEST)
        #将用户的email_active设置True
        user.email_active = True
        user.save()
        #响应结果
        return Response({'message':'OK'})


class EmailView(UpdateAPIView):
    """添加邮箱视图"""
    #指定权限：必须用户登陆后才能访问该接口
    permission_classes = [IsAuthenticated]
    #指定序列化器
    serializer_class = serializers.EmailSerializer

    def get_object(self):
        """在这个方法中返回当前的登陆用户的user信息"""
        return self.request.user





class UserDetailView(RetrieveAPIView):
    """用户基本信息
    必须用户登陆后才能进行访问，因为RetrieveAPIView中的get_object无法获取到pk，所以重写
    """
    #指定权限：必须登陆后才能访问该接口
    prmission_classes = [IsAuthenticated]
    #指定序列化器
    serializer_class = serializers.UserDetailSerializer

    def get_object(self):
        """在这个方法中返回当前的登陆用户的user信息"""
        return self.request.user






#用户注册
# url(r'^users/$', views.UserView.as_view()),
class UserView(CreateAPIView):
    """注册"""
    serializer_class = serializers.CreateUserSerializer


# url(r'^usernames/(?P<username>\w{5,20})/count/$', views.UsernameCountView.as_view()),
class UsernameCountView(APIView):
    """
    用户名数量
    """
    def get(self, request, username):
        """
        获取指定用户名数量
        """
        count = User.objects.filter(username=username).count()

        data = {
            'username': username,
            'count': count
        }

        return Response(data)


# url(r'^mobiles/(?P<mobile>1[3-9]\d{9})/count/$', views.MobileCountView.as_view()),
class MobileCountView(APIView):
    """
    手机号数量
    """
    def get(self, request, mobile):
        """
        获取指定手机号数量
        """
        count = User.objects.filter(mobile=mobile).count()

        data = {
            'mobile': mobile,
            'count': count
        }

        return Response(data)



class AddressViewSet(mixins.CreateModelMixin, mixins.UpdateModelMixin, GenericViewSet):
    """
    用户地址新增与修改
    """
    serializer_class = serializers.UserAddressSerializer
    permissions = [IsAuthenticated]

    def get_queryset(self):
        return self.request.user.addresses.filter(is_deleted=False)

    # GET /addresses/
    def list(self, request, *args, **kwargs):
        """
        用户地址列表数据
        """
        queryset = self.get_queryset()
        serializer = self.get_serializer(queryset, many=True)
        user = self.request.user
        return Response({
            'user_id': user.id,
            'default_address_id': user.default_address_id,
            'limit': constants.USER_ADDRESS_COUNTS_LIMIT,
            'addresses': serializer.data,
        })

    # POST /addresses/
    def create(self, request, *args, **kwargs):
        """
        保存用户地址数据
        """
        # 检查用户地址数据数目不能超过上限UserAddressSerializer
        count = request.user.addresses.count()
        if count >= constants.USER_ADDRESS_COUNTS_LIMIT:
            return Response({'message': '保存地址数据已达到上限'}, status=status.HTTP_400_BAD_REQUEST)

        return super().create(request, *args, **kwargs)

    # delete /addresses/<pk>/
    def destroy(self, request, *args, **kwargs):
        """
        处理删除
        """
        address = self.get_object()

        # 进行逻辑删除
        address.is_deleted = True
        address.save()

        return Response(status=status.HTTP_204_NO_CONTENT)

    # put /addresses/pk/status/
    @action(methods=['put'], detail=True)
    def status(self, request, pk=None):
        """
        设置默认地址
        """
        address = self.get_object()
        request.user.default_address = address
        request.user.save()
        return Response({'message': 'OK'}, status=status.HTTP_200_OK)

    # put /addresses/pk/title/
    # 需要请求体参数 title
    @action(methods=['put'], detail=True)
    def title(self, request, pk=None):
        """
        修改标题
        """
        address = self.get_object()
        serializer = serializers.AddressTitleSerializer(instance=address, data=request.data)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return Response(serializer.data)

from meiduo_mall.apps.carts.utils import merge_cart_cookie_to_redis
from rest_framework_jwt.views import ObtainJSONWebToken
class UserAuthorizeView(ObtainJSONWebToken):
    """
    用户认证
    """
    def post(self, request, *args, **kwargs):
        # 调用父类的方法，获取drf jwt扩展默认的认证用户处理结果
        response = super().post(request, *args, **kwargs)

        # 仿照drf jwt扩展对于用户登录的认证方式，判断用户是否认证登录成功
        # 如果用户登录认证成功，则合并购物车
        serializer = self.get_serializer(data=request.data)
        if serializer.is_valid():
            user = serializer.validated_data.get('user')
            response = merge_cart_cookie_to_redis(request, user, response)

        return response